package types

import (
	"time"

	"github.com/bytedance/sonic"
	"github.com/shopspring/decimal"
)

type Kline struct {
	StockInfo *StockInfo // 股票信息
	KlineInfo KlineInfo
	CCI       float64                    // CCI指标
	MACD      float64                    // MACD指标
	Ma        map[string]decimal.Decimal // 均线数据
}

type KlineInfo struct {
	Timestamp     time.Time       // 时间戳, 单位: 秒
	Open          decimal.Decimal // 开盘价
	High          decimal.Decimal // 最高价
	Low           decimal.Decimal // 最低价
	Close         decimal.Decimal // 收盘价
	LastClose     decimal.Decimal // 昨收价
	Volume        int64           // 成交量
	Amount        decimal.Decimal // 成交额
	TurnoverRate  decimal.Decimal // 换手率
	Amplitude     decimal.Decimal // 振幅
	Change        decimal.Decimal // 涨跌额
	ChangePercent decimal.Decimal // 涨跌幅
}

func (k *KlineInfo) MarshalArray() ([]byte, error) {
	arr := [12]interface{}{
		k.Timestamp.Unix(),
		k.Open,
		k.High,
		k.Low,
		k.Close,
		k.LastClose,
		k.Volume,
		k.Amount,
		k.TurnoverRate,
		k.Amplitude,
		k.Change,
		k.ChangePercent,
	}
	return sonic.Marshal(arr)
}

func (k *KlineInfo) UnmarshalArray(b []byte) error {
	var arr [12]interface{}
	if err := sonic.Unmarshal(b, &arr); err != nil {
		return err
	}
	k.Timestamp = time.Unix(int64(arr[0].(float64)), 0)
	k.Open, _ = decimal.NewFromString(arr[1].(string))
	k.High, _ = decimal.NewFromString(arr[2].(string))
	k.Low, _ = decimal.NewFromString(arr[3].(string))
	k.Close, _ = decimal.NewFromString(arr[4].(string))
	k.LastClose, _ = decimal.NewFromString(arr[5].(string))
	k.Volume = int64(arr[6].(float64))
	k.Amount, _ = decimal.NewFromString(arr[7].(string))
	k.TurnoverRate, _ = decimal.NewFromString(arr[8].(string))
	k.Amplitude, _ = decimal.NewFromString(arr[9].(string))
	k.Change, _ = decimal.NewFromString(arr[10].(string))
	k.ChangePercent, _ = decimal.NewFromString(arr[11].(string))

	return nil
}
